package net.fpeg.kotlin.msa.wordbase.service

import net.fpeg.kotlin.msa.wordbase.dao.WordTagDao
import net.fpeg.kotlin.msa.wordbase.entity.WordBase
import net.fpeg.kotlin.msa.wordbase.entity.WordTag
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import javax.transaction.Transactional

@Service
class WordTagService {
    @Autowired
    lateinit var wordTagDao: WordTagDao

    @Autowired
    lateinit var wordUserService: WordUserService

    @Autowired
    lateinit var wordBaseService: WordBaseService


    fun get(uid: Long, value: String) = wordTagDao.getByWordUser_IdAndValue(uid, value)
    fun getOne(uid: Long, value: String) = get(uid, value) ?: throw Exception("标签不存在")

    fun find(uid: Long, wordValue: String) = wordTagDao.findByWordUser_IdAndValue(uid, wordValue)
    fun find(uid: Long) = wordTagDao.findByWordUser_Id(uid)

    fun add(uid: Long, value: String) = get(uid, value) ?: wordTagDao.save(WordTag(
            value = value,
            wordUser = wordUserService.getOne(uid)
    ))

    fun edit(id: Long, oldValue: String, newValue: String) =
            getOne(id, oldValue).run {
                value = newValue
                wordTagDao.save(this)
            }

    @Transactional
    fun remove(uid: Long, tagValue: String) {
        wordBaseService.remove(wordBaseService.findTag(uid, tagValue))
        wordTagDao.delete(getOne(uid, tagValue))
    }


}